import { defineStore } from 'pinia'
import { setToken, clearToken } from '@/utils/common/auth'

import { UserState } from './types'
import useAppStore from '../app'
import { adminLogin } from '@/api/user/admin-login'
import router from '@/router'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    avatar: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    phone: undefined,
    role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user'
        resolve(this.role)
      })
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial)
    },

    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    // 获取用户信息
    async info() {
      //const res = await getUserInfo()
      //this.setInfo(res.data)
    },

    // 登入系统
    async login(loginForm: { username: string; password: string }) {
      try {
        const res = await adminLogin(loginForm)
        if (res.code == 200) {
          //设置token
          setToken(res.data.accessToken, res.data.refreshToken)
          this.loginSuccessHandle()
        }
      } catch (err) {
        clearToken()
        throw err
      }
    },

    loginSuccessHandle() {
      Promise.all([
        //获取当前用户菜单
        useAppStore().getServerMenuList(),
        //获取当前用户权限
        useAppStore().getServicePermissionList(),
      ]).then(() => {
        console.log(3333333333)

        router.push('/cvmagic/shopinfo')
      })
    },

    /**
     * 退出登入操作
     */
    logoutCallBack() {
      const appStore = useAppStore()
      this.resetInfo()
      clearToken()
      router.push('/cvmagic/login')
    },
    // 退出登入
    async logout() {
      try {
        //await userLogout()
      } finally {
        this.logoutCallBack()
      }
    },
  },
})

export default useUserStore
